#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
拾取窗中流光启动器
检查依赖、处理错误并启动主程序
作者：adnaan
"""

import sys
import os
import subprocess
import importlib
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    print(f"✅ Python版本: {sys.version.split()[0]}")
    return True

def check_dependencies():
    """检查必要依赖"""
    required_packages = [
        ('pystray', 'pystray'),
        ('PIL', 'Pillow'),
        ('psutil', 'psutil'),
        ('win32gui', 'pywin32'),
        ('socketio', 'python-socketio[client]'),
        ('requests', 'requests'),
        ('ttkbootstrap', 'ttkbootstrap'),
    ]
    
    missing_packages = []
    
    for module_name, package_name in required_packages:
        try:
            importlib.import_module(module_name)
            print(f"✅ {package_name}")
        except ImportError:
            missing_packages.append(package_name)
            print(f"❌ {package_name} - 未安装")
    
    return missing_packages

def install_dependencies(packages):
    """安装缺失的依赖"""
    if not packages:
        return True
    
    print(f"\n🔧 正在安装缺失的依赖: {', '.join(packages)}")
    
    try:
        for package in packages:
            print(f"📦 正在安装 {package}...")
            result = subprocess.run([
                sys.executable, '-m', 'pip', 'install', package
            ], capture_output=True, text=True)
            
            if result.returncode == 0:
                print(f"✅ {package} 安装成功")
            else:
                print(f"❌ {package} 安装失败")
                print(f"错误: {result.stderr}")
                return False
        
        print("🎉 所有依赖安装完成")
        return True
        
    except Exception as e:
        print(f"❌ 安装依赖时出错: {e}")
        return False

def main():
    """主启动函数"""
    print("=" * 60)
    print("✨ 拾取窗中流光 v2.0 - 启动器")
    print("✨ 作者: adnaan")
    print("=" * 60)
    
    # 检查Python版本
    if not check_python_version():
        input("按Enter键退出...")
        return
    
    # 检查依赖
    print("\n🔍 检查依赖包...")
    missing = check_dependencies()
    
    if missing:
        print(f"\n⚠️ 发现 {len(missing)} 个缺失的依赖包")
        
        # 询问是否自动安装
        try:
            choice = input("\n是否自动安装缺失的依赖? (y/n): ").lower()
            if choice in ['y', 'yes', '是']:
                if not install_dependencies(missing):
                    print("❌ 依赖安装失败，无法启动程序")
                    input("按Enter键退出...")
                    return
                
                # 重新检查
                print("\n🔍 重新检查依赖...")
                missing = check_dependencies()
                if missing:
                    print("❌ 仍有依赖缺失，请手动安装")
                    input("按Enter键退出...")
                    return
            else:
                print("❌ 缺少必要依赖，无法启动程序")
                print("请手动安装: pip install " + " ".join(missing))
                input("按Enter键退出...")
                return
        except KeyboardInterrupt:
            print("\n👋 用户取消")
            return
    
    # 启动主程序
    print("\n🚀 启动主程序...")
    try:
        # 添加src目录到Python路径
        src_dir = Path(__file__).parent / 'src'
        if src_dir.exists():
            sys.path.insert(0, str(src_dir))
        
        # 导入并运行主程序
        from main import main as run_main
        run_main()
        
    except ImportError as e:
        print(f"❌ 导入主程序失败: {e}")
        print("请确保src/main.py文件存在")
    except Exception as e:
        print(f"❌ 程序运行失败: {e}")
        import traceback
        traceback.print_exc()
    
    input("按Enter键退出...")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n👋 程序被用户中断")
    except Exception as e:
        print(f"❌ 启动器出错: {e}")
        import traceback
        traceback.print_exc()
        input("按Enter键退出...") 